package com.swdegao.iot.netty.udp.server.channelhandler;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSON;
import com.swdegao.iot.SwdegaoIotMgtServerApplication;
import com.swdegao.iot.netty.entity.ImeiInfo;
import com.swdegao.iot.netty.entity.OnOffData;
import com.swdegao.iot.netty.entity.Parameter;
import com.swdegao.iot.netty.utils.Const;
import com.swdegao.iot.netty.utils.RedisUtils;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * @Author:zt
 * @Date: Created in 8:20 2018\10\26 0002
 */

public class HeartBeatClientHandler extends ChannelInboundHandlerAdapter{
	
	//定义一个全局的记录器，通过LoggerFactory获取
    private final static Logger logger = LoggerFactory.getLogger(HeartBeatClientHandler.class); 
	
	@Autowired
    private RedisUtils redisUtils = SwdegaoIotMgtServerApplication.getBean(RedisUtils.class);;
	@Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent){
            IdleStateEvent event = (IdleStateEvent)evt;
            if (event.state()== IdleState.READER_IDLE){
            	logger.info("已经120秒未收到客户端的消息了！");
            	String channelId= Const.getChannelIds(ctx.channel());
            	
            	if("".equals(channelId) || is_heartDelay(channelId)){//已经过期
            		//Const.remove(ctx.channel());
                	ctx.channel().close();
            		//onoffLineAction(channelId,Parameter.reoffline_des);
            	}
            	
            }
        }else {
            super.userEventTriggered(ctx,evt);
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    	ctx.fireChannelRead(msg);
       // System.out.println("client says: "+msg.toString());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
    /**
     * 上线操作
     * @param imei
     * @param channel
     */
    @SuppressWarnings("unused")
	private void onoffLineAction(String imei,String type){
    	OnOffData onOff = new OnOffData();
    	onOff.setImei(imei);
    	onOff.setCreatetime(System.currentTimeMillis());
    	onOff.setAction(type);
    	redisUtils.lPush(imei+Parameter.on_off_info,JSON.toJSONString(onOff));//存储所有updata数据		
    }
    /**
     * 验证心跳是否过期
     * @param imei
     * @return
     */
    private boolean is_heartDelay(String imei){
    	
    	boolean flag = false;
    	try {
    		ImeiInfo imeiInfo = JSON.parseObject(redisUtils.hmGet(Parameter.imei_info,imei).toString(), ImeiInfo.class);
        	int heartbeat_delay_num = imeiInfo.getHeartbeat_delay_num();//获取心跳循环次数
    		int heartbeat_cycle = imeiInfo.getHeartbeat_cycle();
        	if(Parameter.heartbeat_cycle_check * (heartbeat_delay_num + 1) >= heartbeat_cycle*Parameter.heartbeat_delay_num) flag = true;
        	
        	heartbeat_delay_num++;
        	imeiInfo.setHeartbeat_delay_num(heartbeat_delay_num);
        	redisUtils.hmSet(Parameter.imei_info, imei, JSON.toJSONString(imeiInfo));
    	} catch (Exception e) {
			// TODO: handle exception
			flag = true;
		}
    	
    	return flag;
    }

}
